<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-06-29 10:24:20
 * @Description: 店铺授权
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-11-16 15:13:03
 * @FilePath: /qingshanERP/app/Http/Controllers/Home/ShopAuthController.php
 */

namespace App\Http\Controllers\Home;

use App\Customize\Func;
use App\Customize\MyCrypt;
use Illuminate\Http\Request;
use App\Customize\PddRequest;
use App\Models\Tenant\Tenant;
use App\Models\QingShanERP\Shop;
use App\Models\Tenant\TenantLevel;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class ShopAuthController extends Controller
{
    // 发起授权
    public function getPddAuth(Request $req)
    {
        try {
            // $res = ['id' => 1, 'name' => 'pdd11111', 'super' => 1, 'tid' => 1, 'token' => '2222'];
            // dump(json_encode($res));
            // $base = urlencode(MyCrypt::ssl_encrypt(json_encode($res)));
            // dump(base64_decode($base));
            // dump(MyCrypt::ssl_decrypt($base));
            // dd($base);
            $config = config('pdd');
            // $shopid = $req->input('shopid',0);
            // $shop = Shop::where('del_flag',0)->where('status',1)->where(function($q) use($shopid){
            //     if ($shopid != 0) {
            //         $q->where('id', $shopid);
            //     }
            // })->first();
            // if (is_null($shop)) {
            //     exit('没有这个门店，请先在后台添加！');
            // }
            $url = $config['auth_url'][$config['member_type']] . "?response_type=code&client_id=" . $config['client_id'] . "&redirect_uri=" . $config['redirect_uri'];
            return redirect($url);
        } catch (\Throwable $th) {
            // exit('error');
            $url = $config['auth_url'][$config['member_type']] . "?response_type=code&client_id=" . $config['client_id'] . "&redirect_uri=" . $config['redirect_uri'];
            return redirect($url);
        }
    }
    public function getPddCallback(Request $req)
    {
        try {
            $config = config('pdd');
            $code = $req->input('code', '0');
            if ($code == '0') {
                $url = $config['auth_url'][$config['member_type']] . "?response_type=code&client_id=" . $config['client_id'] . "&redirect_uri=" . $config['redirect_uri'];
                return redirect($url);
            }
            // 授权
            $params['code'] = $code;
            $result = PddRequest::request('pdd.pop.auth.token.create', $params);
            if (isset($result['pop_auth_token_create_response'])) {
                // dd($result);
                // 更新门店数据库，redis
                $access_token = $result['pop_auth_token_create_response']['access_token'];
                $expires_at = $result['pop_auth_token_create_response']['expires_at'];
                $shop_name = $result['pop_auth_token_create_response']['owner_name'];
                // 是否有门店
                $shop = Shop::where('shopid', $shop_name)->where('del_flag', 0)->first();
                // 没门店，创建门店与租户
                $crypt = Func::str_random(10);
                $pwd = Func::makepwd('123456', $crypt);
                $level = TenantLevel::where('parent_id', 0)->where('status', 1)->where('del_flag', 0)->first();
                if (is_null($shop)) {
                    $tenant = Tenant::create([
                        'tenant_level_id' => $level->id,
                        'phone' => $shop_name,
                        'tenant_name' => $shop_name,
                        'email' => 'test@test.com',
                        'crypt' => $crypt,
                        'password' => $pwd,
                        'last_date' => date('Y-m-d H:i:s', time() + $level->days * 3600 * 24),
                        'status' => 1,
                        'del_flag' => 0
                    ]);
                    $shop = Shop::create(['tenant_id' => $tenant->id, 'type' => 4, 'shopname' => $shop_name, 'shopid' => $shop_name, 'access_token' => $access_token, 'expires_at' => $expires_at, 'super_flag' => 1, 'status' => 1, 'del_flag' => 0]);
                } else {
                    // 删除旧的token，并写入新的有效期内的token
                    Redis::del('shop-token:' . $shop_name);
                    if ($shop->status != 1) {
                        exit('门店（' . $shop_name . '）已经被禁用，请联系系统客服（18932813211）恢复使用权限！');
                        $url = config('app.url') . '/tenant.html';
                        return redirect($url);
                    }
                    // 找租户信息
                    if ($shop->tenant_id == 0) {
                        $tenant = Tenant::create(['tenant_level_id' => $level->id, 'phone' => $shop_name, 'tenant_name' => $shop_name, 'email' => 'test@test.com', 'crypt' => $crypt, 'password' => $pwd, 'last_date' => date('Y-m-d H:i:s', time() + $level->days * 3600 * 24), 'status' => 1, 'del_flag' => 0]);
                        // 更新门店token
                        Shop::where('id', $shop->id)->update(['tenant_id' => $tenant->id, 'super_flag' => 1, 'access_token' => $access_token, 'expires_at' => $expires_at]);
                    } else {
                        // 看租户是否过期
                        $tenant = Tenant::where('id', $shop->tenant_id)->first();
                        if (strtotime($tenant->last_date) <= time()) {
                            exit('门店（' . $shop_name . '）权益已到期，请联系客服（18932813211）升级门店租户级别！');
                            $url = config('app.url') . '/tenant.html';
                            return redirect($url);
                        }
                        // 更新门店token
                        Shop::where('id', $shop->id)->update(['access_token' => $access_token, 'expires_at' => $expires_at]);
                    }
                }
                Redis::setex('shop-token:' . $shop_name, $expires_at - time(), $access_token);
                // exit('授权成功，请关闭页面！');
                $token = md5(md5($shop->id . '-TENANT-' . $shop->shopid));
                // 放到redis里边，先删除旧的，有效期一天
                Redis::del('t-token:' . $token);
                $res = ['id' => $shop->id, 'name' => $shop->shopid, 'super' => $shop->super_flag, 'tid' => $tenant->id, 'token' => $token];
                Redis::setex('t-token:' . $token, 3600 * 24, json_encode($res));
                // 加密、URL编码
                $base = urlencode(MyCrypt::ssl_encrypt(json_encode($res)));
                $url = config('app')['url'] . '/tenant.html#/auth/login?param=' . $base;
                return redirect($url);
            } else {
                // dd($result['error_response']['error_msg'] . '，请稍后再试！');
                $url = $config['auth_url'][$config['member_type']] . "?response_type=code&client_id=" . $config['client_id'] . "&redirect_uri=" . $config['redirect_uri'];
                return redirect($url);
            }
        } catch (\Throwable $th) {
            // dd($th->getLine().' - '.$th->getMessage());
            $url = $config['auth_url'][$config['member_type']] . "?response_type=code&client_id=" . $config['client_id'] . "&redirect_uri=" . $config['redirect_uri'];
            return redirect($url);
        }
    }
    public function getPddCallbackBack(Request $req)
    {
        try {
            $config = config('pdd');
            $code = $req->input('code', '0');
            if ($code == '0') {
                // exit('本页面不能直接打开，请先授权！');
                $url = $config['auth_url'][$config['member_type']] . "?response_type=code&client_id=" . $config['client_id'] . "&redirect_uri=" . $config['redirect_uri'];
                return redirect($url);
            }
            $shopid = $req->input('state', '0');
            $shop = Shop::where('del_flag', '0')->where('status', 1)->where(function ($q) use ($shopid) {
                if ($shopid != 0) {
                    $q->where('id', $shopid);
                }
            })->first();
            if (is_null($shop)) {
                // exit('没有这个门店，请先在后台添加！');
                $url = $config['auth_url'][$config['member_type']] . "?response_type=code&client_id=" . $config['client_id'] . "&redirect_uri=" . $config['redirect_uri'];
                return redirect($url);
            }
            // 授权
            $params['code'] = $code;
            $result = PddRequest::request('pdd.pop.auth.token.create', $params);
            if (isset($result['pop_auth_token_create_response'])) {
                // 更新门店数据库，redis
                $access_token = $result['pop_auth_token_create_response']['access_token'];
                $expires_at = $result['pop_auth_token_create_response']['expires_at'];
                Shop::where('id', $shopid)->update(['access_token' => $access_token, 'expires_at' => $expires_at]);
                // 删除旧的token，并写入新的有效期内的token
                Redis::del('shop-token:' . $shopid);
                Redis::setex('shop-token:' . $shopid, $expires_at - time(), $access_token);
                // exit('授权成功，请关闭页面！');
                $url = config('app')['url'] . '/console.html#/order/pddlist';
                return redirect($url);
            } else {
                exit($result['error_response']['error_msg'] . '，请稍后再试！');
            }
        } catch (\Throwable $th) {
            exit('error');
        }
    }
}
